from django.shortcuts import render

# Create your views here.
from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View

from areas.models import Area
from utils.response_code import RET


class AreasView(View):
    def get(self, request):
        # 1, 初始化数据, 获取参数, 和校验参数
        area_id = request.GET.get('area_id')

        # 2, 处理业务逻辑
        if not area_id:
            # 获取省份数据
            """
            {
              "code":"0",
              "errmsg":"OK",
              "province_list":[
                  {
                      "id":110000,
                      "name":"北京市"
                  },
                  ....
              ]
            }"""
            p_list = cache.get('province_list')
            if not p_list:
                provinces = Area.objects.filter(parent__isnull=True)

                p_list = []
                for p in provinces:
                    p_data = {'id': p.id, 'name': p.name}
                    p_list.append(p_data)

                cache.set('province_list', p_list, 3600)  #存起来放在redis里缓存的数据
            else:
                pass

            res = {
                "code": "0",
                "errmsg": "OK",
                "province_list": p_list
            }
            return http.JsonResponse(res)

        else:
            # 获取市区的数据
            sub_data = cache.get('sub_data_%s' % area_id)
            if not sub_data:
                try:
                    area = Area.objects.get(id=area_id)
                except Exception as e:
                    return http.JsonResponse({'code': RET.PARAMERR, 'errmsg': '区域id错误'})

                area_subs = area.subs.all()

                """
                {
                  "code":"0",
                  "errmsg":"OK",
                  "sub_data":{
                      "id":130000,
                      "name":"河北省",
                      "subs":[
                          {
                              "id":130100,
                              "name":"石家庄市"
                          },
                          ......
                      ]
                  }
                }
                """
                subs = []
                for a in area_subs:
                    area_data = {"id": a.id, 'name': a.name}
                    subs.append(area_data)

                sub_data = {
                    "id": area.id,
                    "name": area.name,
                    "subs": subs
                }

                cache.set('sub_data_%s' % area_id, sub_data, 3600)

            res = {
                "code": "0",
                "errmsg": "OK",
                "sub_data": sub_data
            }
            return http.JsonResponse(res)

        # 3, 返回响应
        pass